/**
 * API 接口配置文件
 */

// 开发环境和生产环境的 API 基础地址
// 所有请求通过网关转发
const BASE_URL = process.env.NODE_ENV === 'development' 
  ? 'http://localhost:8083/api'  // 开发环境 - 通过网关
  : 'https://your-domain.com/api'  // 生产环境

/**
 * 封装 uni.request
 */
const request = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: (/^https?:\/\//.test(options.url) ? options.url : (BASE_URL + options.url)),
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        'Authorization': uni.getStorageSync('token') || ''
      },
      success: (res) => {
        if (res.statusCode === 200) {
          // 根据后端约定的数据格式处理
          if (res.data.code === 200 || res.data.code === 0 || res.data.success) {
            resolve(res.data.data || res.data)
          } else {
            uni.showToast({
              title: res.data.message || '请求失败',
              icon: 'none'
            })
            reject(res.data)
          }
        } else if (res.statusCode === 401) {
          // 未授权，跳转登录
          uni.navigateTo({
            url: '/pages/page3/page3'
          })
          reject(res)
        } else {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(err)
      }
    })
  })
}

/**
 * API 接口列表
 */
export default {
  // 地区
  area: {
    // 不用省份，直接拉城市
    getCities: () => request({ url: '/recommend/area/cities' }),
    getAreas: (cityId) => request({ url: `/recommend/area/areas?cityId=${cityId}` })
  },
  // 用户相关
  user: {
    // 获取用户信息
    getInfo: () => request({ url: '/user/info' }),
    
    // 获取今日匹配数
    getMatchCount: () => request({ url: '/user/match-count' }),
    
    // 更新用户信息
    updateInfo: (data) => request({ 
      url: '/user/info', 
      method: 'PUT', 
      data 
    })
  },

  // 认证相关
  auth: {
    // 密码登录（手机号+密码）
    loginByPassword: (phone, password) => request({
      // 直连 login 服务（开发环境），避免网关未配置导致未路由
      url: 'http://localhost:8087/api/login/password',
      method: 'POST',
      data: { phone, password }
    }),

    // 发送登录验证码（走网关 -> 登录服务）
    sendCode: (phone) => request({
      url: '/login/send-code',
      method: 'POST',
      data: { phone }
    }),

    // 验证码登录（走网关 -> 登录服务）
    smsLogin: (phone, code) => request({
      url: '/login/sms-login',
      method: 'POST',
      data: { phone, code }
    }),

    // 微信登录（直连 login 服务以便开发环境不依赖 appid/secret 配置）
    wechatLogin: (code) => request({
      url: 'http://localhost:8087/api/login/wechat/login',
      method: 'POST',
      data: { code }
    }),

    // 获取微信手机号（直连 login 服务）
    wechatPhone: (code) => request({
      url: 'http://localhost:8087/api/login/wechat/phone',
      method: 'POST',
      data: { code }
    })
  },

  // 首页相关
  home: {
    // 获取轮播图
    getBanners: () => request({ url: '/home/banners' }),
    
    // 获取公告列表
    getNotices: () => request({ url: '/home/notices' }),
    
    // 获取未读消息数
    getUnreadCount: () => request({ url: '/home/unread-count' })
  },

  // 成功案例
  successCase: {
    // 获取成功案例列表
    getList: (params) => request({ 
      url: '/success-case/list',
      method: 'GET',
      data: params 
    }),
    
    // 获取成功案例详情
    getDetail: (caseNo) => request({ 
      url: `/success-case/detail/${caseNo}`,
      method: 'GET'
    }),
    
    // 获取案例时间线
    getTimeline: (caseNo) => request({ 
      url: `/success-case/timeline/${caseNo}`,
      method: 'GET'
    })
  },

  // 活动相关
  activity: {
    // 获取活动列表
    getList: (params) => request({ 
      url: '/activity/list',
      method: 'GET',
      data: params 
    }),
    
    // 获取活动详情
    getDetail: (id) => request({ 
      url: `/activity/detail/${id}`,
      method: 'GET'
    }),
    
    // 报名活动
    register: (activityId, userId) => request({ 
      url: `/activity/register/${activityId}?userId=${userId}`, 
      method: 'POST'
    }),
    
    // 取消报名
    cancelRegister: (activityId) => request({ 
      url: `/activity/cancel/${activityId}`, 
      method: 'POST' 
    })
  },

  // 课程相关
  course: {
    // 获取课程列表
    getList: (params) => request({ 
      url: '/course/list',
      method: 'GET',
      data: params 
    }),
    
    // 获取课程详情
    getDetail: (id) => request({ 
      url: `/course/detail/${id}`,
      method: 'GET'
    }),
    
    // 购买课程
    purchase: (courseId, data) => request({ 
      url: `/course/purchase/${courseId}`, 
      method: 'POST', 
      data 
    })
  },

  // 红娘相关
  matchmaker: {
    // 获取红娘列表
    getList: (params) => request({ 
      url: '/matchmaker/list', 
      method: 'POST',
      data: params 
    }),
    
    // 获取全职红娘列表
    getFormalList: (pageNum, pageSize) => request({ 
      url: `/matchmaker/formal?pageNum=${pageNum}&pageSize=${pageSize}` 
    }),
    
    // 获取红娘详情
    getDetail: (id) => request({ 
      url: `/matchmaker/detail/${id}` 
    }),
    
    // 预约红娘
    book: (matchmakerId, data) => request({ 
      url: `/matchmaker/book/${matchmakerId}`, 
      method: 'POST', 
      data 
    })
  },

  // 推荐相关
  recommend: {
    // 获取推荐用户列表（网关转发到推荐服务）
    getUsers: ({ userId, oppoOnly = 1, limit = 20 }) => request({
      url: `/recommend/users?userId=${userId}&oppoOnly=${oppoOnly}&limit=${limit}`
    }),
    // 行为反馈：like/dislike
    feedback: ({ userId, targetUserId, type }) => request({
      url: `/recommend/feedback?userId=${userId}&targetUserId=${targetUserId}&type=${type}`
    }),
    // 曝光上报
    exposure: ({ userId, shownUserIds }) => request({
      url: `/recommend/exposure?userId=${userId}&shownUserIds=${encodeURIComponent(shownUserIds)}`
    }),
    // 规则检索
    search: (query) => request({
      url: '/recommend/search',
      method: 'POST',
      data: query
    }),
    // 获取今日推荐
    getTodayRecommend: () => request({ 
      url: '/recommend/today' 
    })
  },

  // 消息相关
  message: {
    // 获取消息列表
    getList: (params) => request({ 
      url: '/message/list', 
      data: params 
    }),
    
    // 获取会话列表
    getConversations: () => request({ 
      url: '/message/conversations' 
    }),
    
    // 发送消息
    send: (data) => request({ 
      url: '/message/send', 
      method: 'POST', 
      data 
    })
  },

  // 动态相关
  dynamic: {
    // 获取推荐动态列表（广场）
    getRecommendList: (params) => request({
      url: '/dynamic/recommend',
      data: params
    }),

    // 获取动态列表
    getList: (params) => request({
      url: '/dynamic/list',
      data: params
    }),

    // 获取动态详情
    getDetail: (dynamicId, userId) => request({
      url: `/dynamic/detail/${dynamicId}`,
      data: { userId }
    }),
    // 发表评论
    addComment: (dynamicId, content, images, parentCommentId = 0) => request({
      url: `/dynamic/comment`,
      method: 'POST',
      data: { dynamicId, content, images, parentCommentId, userId: 1 },
      header: { 'Content-Type': 'application/json' }
    }),

    // 评论列表
    getComments: (dynamicId, pageNum = 1, pageSize = 10) => request({
      url: `/dynamic/comment/list/${dynamicId}`,
      data: { pageNum, pageSize }
    }),

    // 评论点赞/取消
    likeComment: (commentId) => request({
      url: `/dynamic/comment/like?commentId=${commentId}&userId=1`,
      method: 'POST'
    }),
    unlikeComment: (commentId) => request({
      url: `/dynamic/comment/like/${commentId}?userId=1`,
      method: 'DELETE'
    }),


    // 获取用户动态列表
    getUserDynamics: (userId, params) => request({
      url: `/dynamic/user/${userId}`,
      data: params
    }),

    // 点赞动态
    like: (dynamicId) => request({
      url: `/dynamic/like?dynamicId=${dynamicId}&userId=1`,
      method: 'POST'
    }),

    // 取消点赞
    unlike: (dynamicId) => request({
      url: `/dynamic/like/${dynamicId}`,
      method: 'DELETE'
    }),

    // 收藏动态
    favorite: (dynamicId) => request({
      url: `/dynamic/favorite?dynamicId=${dynamicId}&userId=1`,
      method: 'POST'
    }),

    // 取消收藏
    unfavorite: (dynamicId) => request({
      url: `/dynamic/favorite/${dynamicId}`,
      method: 'DELETE'
    }),

    // 发布动态
    publish: (data) => request({
      url: '/dynamic/publish',
      method: 'POST',
      data
    }),

    // 删除动态
    delete: (dynamicId) => request({
      url: `/dynamic/${dynamicId}`,
      method: 'DELETE'
    }),

    // 发布动态（文本或已存在的媒体URL列表）
    publish: (payload) => request({
      url: '/dynamic/publish',
      method: 'POST',
      data: payload,
      header: { 'Content-Type': 'application/json' }
    }),

    // 单个文件上传方法
    uploadSingle: (filePath) => {
      return new Promise((resolve, reject) => {
        console.log('开始上传文件:', filePath)
        console.log('上传URL:', BASE_URL + '/dynamic/publish/upload')

        uni.uploadFile({
          url: BASE_URL + '/dynamic/publish/upload',
          filePath: filePath,
          name: 'file',
          header: {
            'Content-Type': 'multipart/form-data'
          },
          success: (res) => {
            console.log('上传响应:', res)
            try {
              const data = JSON.parse(res.data)
              console.log('解析后的响应数据:', data)

              if (data.code === 200 || data.code === 0 || data.success) {
                console.log('上传成功，返回URL:', data.data)
                resolve(data.data)
              } else {
                console.error('上传失败，服务器返回错误:', data)
                reject(new Error(data.message || '上传失败'))
              }
            } catch (e) {
              console.error('解析响应数据失败:', e, '原始响应:', res.data)
              reject(new Error('解析响应数据失败'))
            }
          },
          fail: (error) => {
            console.error('上传请求失败:', error)
            reject(new Error('上传请求失败: ' + (error.errMsg || '未知错误')))
          }
        })
      })
    },

    // 批量上传多个文件（遍历调用单个上传）
    uploadBatch: (filePaths) => {
      return new Promise(async (resolve, reject) => {
        const urls = []
        try {
          for (let filePath of filePaths) {
            const url = await new Promise((resolveUpload, rejectUpload) => {
              uni.uploadFile({
                url: BASE_URL + '/dynamic/publish/upload',
                filePath: filePath,
                name: 'file',
                header: {
                  'Content-Type': 'multipart/form-data'
                },
                success: (res) => {
                  try {
                    const data = JSON.parse(res.data)
                    if (data.code === 200 || data.code === 0 || data.success) {
                      resolveUpload(data.data)
                    } else {
                      rejectUpload(data)
                    }
                  } catch (e) {
                    rejectUpload(e)
                  }
                },
                fail: rejectUpload
              })
            })
            urls.push(url)
          }
          resolve(urls)
        } catch (e) {
          reject(new Error(`批量上传失败: ${e.message || '未知错误'}`))
        }
      })
    }
  }
}

// 导出 request 函数供其他模块使用
export { request }
